define([
     "dojo/_base/declare",
     "gistech/widgets/baseWidget/BaseWidget",
     "gistech/widgets/normalDialog/NormalDialog",
     "dojo/text!./templates/template.html",
     "../../../app/UIManager",
     "gistech/widgets/FileUpload/FileUpload",
     "dojo/_base/lang",
     "../../util/ajaxUtil",
     "dojo/topic",
     "dojo/dom-style",
     "dojo/dom-construct",
     "dojo/on",
     "dojo/_base/connect",
     ],function(declare,BaseWidget,NormalDialog,template,UIManager,FileUpload,lang,ajaxUtil,Topic,style,domConstruct,on,eventconnect){
	    return declare([NormalDialog],{
	    	templateString:template,
	    	message:null,
	    	isManager:false,
	    	messageArray:null,
	    	pageNum:0,
	    	nOfPage:5,
	    	pageCount:null,
	    	constructor:function(args){
	    		this.inherited(arguments);
	    		this.message=$.parseJSON(args);
	    		this.isManager=ioc.map.userInfoData.isManager?true:false;
	    	},
	    	postCreate:function(){
                this.inherited(arguments);
                if(this.message!=null){this.initMessageWindow(this.message);}else{this.showMessList();}
                $(this.domNode).css('width','600px');
            },
            putFileUploadToPanel:function(){
            	debugger
            	if(dijit.byId("attchment")){
            		return false;
            	}else{
            		var fileUploadWidget=new FileUpload({id:"attchment","who":"Message","ownerId":this.message.id});
                	fileUploadWidget.setTitle("附件上传");
                	fileUploadWidget.startup();
            	}
            },
            refreshGetAllMessage:function(){
            	dojo.empty(this.tbody);
            	ajaxUtil.request("../client/backgroundManagement/MessageController/allMessage","",lang.hitch(this,function(res){
            		this.messageArray=res;
            		this.pageCount=Math.ceil(res.length/this.nOfPage);
            		this.firstPage();
        		}));
            },
            
            firstPage:function(){
            	this.pageNum=1;
            	var currentMessages=this.messageArray.slice(this.nOfPage*(this.pageNum-1),this.nOfPage*this.pageNum);
            	this.createWithCurrMessages(currentMessages);
            },
            deleteFormAllMessage:function(id){
            	debugger
            	ajaxUtil.request("../client/backgroundManagement/MessageController/deleteMessage","id="+id,lang.hitch(this,function(e){
            		if(e.success==true){
            			layer.msg("删除成功",{icon:1});
            			this.pageNum--;
            			this.refreshGetAllMessage();
            		}else{
            			layer.msg("删除失败",{icon:2});
            		}
            	}))
            },
            initMessageWindow:function(mess){
            	this.message=mess;
            	this.domNode.querySelector("#title").value=mess.title;
            	this.domNode.querySelector("#mess_id").value=mess.id;
            	this.domNode.querySelector("#text-content").value=mess.content;
            	this.domNode.querySelector("#pbUserName").value=mess.pbUserName;
            	this.domNode.querySelector("#pbTime").value=mess.pbtime;
            	if(mess.attachments.length>0){
            		$("#user").css("display","none");
            		$("#time").css("display","none");
            		$("#attachmentPanel").css("display","block");
            		this.setAttachmentIntoPanel(mess.attachments);
            	}else{
            		$("#user").css("display","block");
            		$("#time").css("display","block");
            		$("#attachmentPanel").css("display","none");
            	}
            	if(this.editAble(mess)==true){this.edit.disabled=false;}else{this.edit.disabled=true;}
            },
            setAttachmentIntoPanel:function(attachments){
            	$("#attachmentPanel").empty();
            	dojo.forEach(attachments,lang.hitch(this,function(item,index){
            		debugger
            		var $row=$(".tempCon #temp").clone(true);
            		if(item.fileType=="image/png"){
                        $row.find("img").attr("src","../client/images/pic.png");
                        $row.find("#fileName").text(item.fileName);
            		}else if(item.fileType=="application/pdf"){
            			$row.find("img").attr("src","../client/images/pdf.png");
                        $row.find("#fileName").text(item.fileName);
            		}
            		$row.find(".action_view").bind("click",lang.hitch(this,function(){
            			this.inlineview(item.filePath,item.fileName,item.fileType);
            		}));
            		debugger
            		$row.find("#downFlagCheckBox").attr("checked",item.flag==1?"checked":undefined)
            		$row.find(".action_down").bind("click",lang.hitch(this,function(){
            			if(item.flag=="0"){layer.msg("此资源不允许下载，请联系管理员",{icon:2});}else{this.downloadFile(item.filePath,item.fileName);}}));
            		$row.find(".action_delete").bind("click",lang.hitch(this,function(){
            			layer.confirm('确定删除该附件？', {
            				  btn: ['是的','算了'] //按钮
            				}, lang.hitch(this,function(){this.deleteAttachmentBy(item.filePath,item.id,$row)}),
            				   lang.hitch(this,function(){layer.closeAll("dialog")}));
            		    }))
            		$row.find("#downFlagCheckBox").change(lang.hitch(this,function(e){
            			debugger
            			if($(e.target).is(":checked")==true){
            				this.updateAttachmentDownStatus(item.id,1);
            			}else{
            				this.updateAttachmentDownStatus(item.id,0);
            			}
            		}))
            		$row.appendTo($("#attachmentPanel"));
            	}))
            },
            updateAttachmentDownStatus:function(id,status){
            	debugger
            	$.post("../client/backgroundManagement/AttachmentController/updateAttachmentDownStatusById?id="+id+"&status="+status,function(res){
            		res=$.parseJSON(res);
            		debugger
            		if(res.success==true){
            			layer.msg(res.msg,{icon:1});
            		}else{
            			layer.msg(res.msg,{icon:2});
            		}
            		
            	});
            },
            deleteAttachmentBy:function(path,id,dom){
            	if(this.editAble(this.message)){
            		debugger
            		$.post("../client/backgroundManagement/AttachmentController/deleteAttachmentById?path="+path+"&id="+id+"",function(res){
                		layer.closeAll("dialog");
                		res=$.parseJSON(res);
                		if(res.success==true){
                			dom.remove();
                		}else{
                			layer.msg(res.msg,{icon:1});
                			dom.remove();
                		}
                	})
            	}else{
            		layer.msg("没有权限",{icon:2});
            	}
            },
            inlineview:function(path,name,type){
            	if(type=="image/png"){
            		layer.open({
                		type: 2,
                	    title: name,
                	    shadeClose: true,
            	        shade: false,
            	        maxmin: true, //开启最大化最小化按钮
            	        area: ['800px', '600px'],
            	        content: "../client/backgroundManagement/AttachmentController/getAttachByPath?path="+path+"&online=true"
                	})
            	}else if(type=="application/pdf"){
            		layer.open({
                		type: 2,
                	    title: name,
                	    shadeClose: true,
            	        shade: false,
            	        maxmin: true, //开启最大化最小化按钮
            	        area: ['893px', '600px'],
            	        content: "../client/gistech/lib/pdfjs/web/viewer.html?path=http://localhost:8080/sddc/client/backgroundManagement/AttachmentController/getAttachByPath?path="+path+""
                	})
            	}
            },
            downloadFile:function(path,name){
            	debugger
            	var form=this.downLoadForm;
            	var url="../client/backgroundManagement/AttachmentController/downAttachByPath?path="+path+"&name="+name+"";
            	form.action=url;
            	form.submit();
            },
            nextPage:function(){
            	this.pageNum++;//1
            	if(this.pageNum>this.pageCount){
            		this.next.disabled=true;
            		this.pageNum--;
            		return false;
            	}else{
            		this.previous.disabled=false;
            	}
            	var currentMessages=this.messageArray.slice(this.nOfPage*(this.pageNum-1),this.nOfPage*this.pageNum);
            	this.createWithCurrMessages(currentMessages);
            },
            previousPage:function(){
            	this.pageNum--;
            	if(this.pageNum<1){
            		this.previous.disabled=true;
            		this.pageNum++;
            		return false;
            	}else{
            		this.next.disabled=false;
            	}
            	var currentMessages=this.messageArray.slice(this.nOfPage*(this.pageNum-1),this.nOfPage*this.pageNum);
            	this.createWithCurrMessages(currentMessages);
            },
            createWithCurrMessages:function(messArr){
            	dojo.empty(this.tbody);
            	dojo.forEach(messArr,lang.hitch(this,function(item,index){
        			var trtag=dojo.create("tr",{id:item.id});
        			var tdtag1=dojo.create("td",{innerHTML:item.title,style:{cursor:"pointer",maxWidth: "200px"}});
        			var tdtag2=dojo.create("td",{innerHTML:item.pbUserName});
        			var tdtag3=dojo.create("td",{innerHTML:item.pbtime});
        			var tdtag4=dojo.create("td");
        			var div=dojo.create("div",{style:{width:"60px"}});
        			var btnShow=dojo.create("input",{type:"checkbox",name:"checkBox",id:item.id,value:item.status,style:{width:"30px"}});
        			var btnDelete=dojo.create("span",{class:"glyphicon glyphicon-remove",style:{top:0}});
        			domConstruct.place(btnShow,div);
        			domConstruct.place(btnDelete,div);
        			domConstruct.place(div,tdtag4);
        			domConstruct.place(tdtag1,trtag);
        			domConstruct.place(tdtag2,trtag);
        			domConstruct.place(tdtag3,trtag);
        			domConstruct.place(tdtag4,trtag);
        			domConstruct.place(trtag,this.tbody);
        			$("[name='checkBox'][value='1']").attr("checked","true");
        			$(btnShow).bind("click",lang.hitch(this,function(e){
        				if(e.currentTarget.checked==true){
        					this.updateMessageStatus(e.currentTarget.id,'1');
        			    }else{
        			    	this.updateMessageStatus(e.currentTarget.id,'0'); 
        			    }
        			}))
        			$(tdtag1).bind("click",lang.hitch(this,function(e){
        				this.getAttachByMessageId(item.id);
        			}));
        			$(btnDelete).bind("click",lang.hitch(this,function(e){
        				 debugger
                         this.deleteFormAllMessage(item.id);
        			}));
        			if(this.isManager==false){
        				$(btnShow).attr("disabled",true);
        				$(btnDelete).unbind("click");
        			}
        		}))
            },
            getAttachByMessageId:function(id){
            	$.get("../client/backgroundManagement/MessageController/getMessageById",{id:id},lang.hitch(this,function(res){
            		this.initMessageWindow($.parseJSON(res));
            		this.showMessList();
            	}));
            },
            updateMessageStatus:function(id,flag){
            	$.ajax({
            		url:"../client/backgroundManagement/MessageController/updateMessageStatus",
            		data:{"id":id,"status":flag},
            		type:"POST",
            		async:true,
            		dataType:"json",
            		success:function(res){
            			console.log(res.msg)
            		},
            		error:function(){
            			layer.msg("操作失败",{icon:2});
            		}
            	})
            },
            startup:function(){
            	debugger
                this.inherited(arguments);
            	dojo.query(".mainContainer").style({height:"400px",overflow:"hidden"})
                on(this.edit,"click",lang.hitch(this,this.activeEdit));
                on(this.close,"click",lang.hitch(this,this.closeDialog));
                on(this.manage,"click",lang.hitch(this,this.showMessList));
                on(this.next,"click",lang.hitch(this,this.nextPage));
                on(this.previous,"click",lang.hitch(this,this.previousPage));
                this.deactiveEdit();
                
            },
            showMessList:function(){
            	this.deactiveEdit();
            	if(this.manage.innerHTML=="列表管理"){
            		this.refreshGetAllMessage();
                	$(".form-horizontal").animate({"marginLeft":"-600px"},"normal");
                	this.manage.innerHTML="返回详情"
            	}else if(this.manage.innerHTML=="返回详情"){
            		if(this.domNode.querySelector("#mess_id").value==""){
            			layer.tips('点击消息标题以查看详情', '.manager', {
            				  tips: [4, '#78BA32']
            				})
            			return false;
            		}else{
            			$(".form-horizontal").animate({"marginLeft":"0px"},"normal");
                		this.manage.innerHTML="列表管理";
            		}
            	}
            },
            editAble:function(mess){
            	if(ioc.map.userInfoData.DISPLAYNAME=="管理员"||mess.pbUserId==ioc.map.userInfoData.USERID){
            		return true;
            	}else{
            		return false;
            	}
            },
            deactiveEdit:function(){
            	this.title.disabled=true;
            	this.textContent.disabled=true;
            	this.pbUserName.disabled=true;
            	this.pbTime.disabled=true;
            },
            activeEdit:function(){
            	if(this.edit.innerHTML=="编辑"){
            		this.title.disabled=false;
                	this.textContent.disabled=false;
                	this.edit.innerHTML="确定";
                	$("#attachmentPanel .editStatus").css("display","block");
                	$("#attachmentPanel .showStatus").css("display","none");
                	on(this.attachment,"click",lang.hitch(this,this.putFileUploadToPanel));
            	}else if(this.edit.innerHTML=="确定"){
            		this.pbMessage();
            	}
            },
            toggleDeleteBtnAction:function(){
            	debugger
            },
            pbMessage:function(){
            	var self=this;
            	debugger
            	if($("#title").val().trim(" ")!=""){
            		$.ajax({
            			type:"POST",
            			async:false,
            			url:"../client/backgroundManagement/MessageController/updateMessage",
            			data:{id:$("#mess_id").val(),title:$("#title").val(),content:$("#text-content").val(),userId:ioc.map.userInfoData.USERID,userName:ioc.map.userInfoData.USERNAME},
            			dataType:"json",
            			success:function(res){
            				debugger
            				layer.msg("更新成功",{icon:1});
            			    self.closeDialog();},
            			error:function(){
            				layer.msg("更新失败",{icon:2});}})
            	}else{
            		layer.msg("内容不规范",{icon:2});}
            },
            resetAttr:function(){
            	$("#title").val("");
            	$("#text-content").val("");
            },
            closeDialog:function(){
            	Topic.publish("RefreshMessageBox","refresh");
    			this.inherited(arguments);
    			this.destroy();
    		},
    		
	    })
     })